<template>
  <div class="sql-history">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>SQL历史记录</span>
          <div>
            <el-select 
              v-model="filters.database_id" 
              placeholder="数据库筛选"
              style="width: 200px; margin-right: 10px"
              clearable
              @change="loadHistory"
            >
              <el-option
                v-for="db in databases"
                :key="db.id"
                :label="`${db.name} (${db.host}:${db.port})`"
                :value="db.id"
              />
            </el-select>
            <el-button @click="loadHistory" :loading="loading">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table :data="history" border style="width: 100%">
        <el-table-column prop="user.username" label="执行用户" width="120" />
        <el-table-column prop="database_instance.name" label="数据库" width="150" />
        <el-table-column label="SQL内容" width="300">
          <template #default="{ row }">
            <div class="sql-content" @click="viewSQL(row)">
              {{ truncateSQL(row.sql_content) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="execution_time" label="执行时间(s)" width="120">
          <template #default="{ row }">
            <el-tag :type="getExecutionTimeTag(row.execution_time)">
              {{ row.execution_time }}s
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rows_affected" label="影响行数" width="100" />
        <el-table-column prop="is_success" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_success ? 'success' : 'danger'">
              {{ row.is_success ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip_address" label="IP地址" width="140" />
        <el-table-column prop="created_at" label="执行时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewSQL(row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px; text-align: center">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="loadHistory"
        />
      </div>
    </el-card>

    <!-- SQL详情对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="SQL详情"
      width="70%"
      destroy-on-close
    >
      <div v-if="currentSQL">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="执行用户">
            {{ currentSQL.user?.username }}
          </el-descriptions-item>
          <el-descriptions-item label="数据库">
            {{ currentSQL.database_instance?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="执行时间">
            <el-tag :type="getExecutionTimeTag(currentSQL.execution_time)">
              {{ currentSQL.execution_time }}s
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="影响行数">
            {{ currentSQL.rows_affected }}
          </el-descriptions-item>
          <el-descriptions-item label="执行状态">
            <el-tag :type="currentSQL.is_success ? 'success' : 'danger'">
              {{ currentSQL.is_success ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ currentSQL.ip_address }}
          </el-descriptions-item>
          <el-descriptions-item label="执行时间" :span="2">
            {{ formatDate(currentSQL.created_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px">
          <h4>SQL内容：</h4>
          <el-input
            :model-value="currentSQL.sql_content"
            type="textarea"
            :rows="10"
            readonly
            style="font-family: 'Courier New', monospace"
          />
        </div>

        <div v-if="!currentSQL.is_success && currentSQL.error_message" style="margin-top: 20px">
          <h4>错误信息：</h4>
          <el-alert
            :title="currentSQL.error_message"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { sqlAPI } from '../../api/sql'

const history = ref([])
const databases = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const filters = reactive({
  database_id: ''
})

const dialogVisible = ref(false)
const currentSQL = ref(null)

const loadDatabases = async () => {
  try {
    const response = await sqlAPI.getDatabaseInstances()
    databases.value = response.results || response
  } catch (error) {
    console.error('加载数据库实例失败:', error)
  }
}

const loadHistory = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }
    
    if (filters.database_id) {
      params.database_id = filters.database_id
    }
    
    const response = await sqlAPI.getSQLHistory(params)
    history.value = response.results || response
    total.value = response.count || 0
  } catch (error) {
    console.error('加载SQL历史失败:', error)
    ElMessage.error('加载SQL历史失败')
  } finally {
    loading.value = false
  }
}

const viewSQL = (sqlRecord) => {
  currentSQL.value = sqlRecord
  dialogVisible.value = true
}

const truncateSQL = (sql) => {
  if (sql.length > 100) {
    return sql.substring(0, 100) + '...'
  }
  return sql
}

const getExecutionTimeTag = (time) => {
  if (time < 0.1) return 'success'
  if (time < 1) return 'warning'
  return 'danger'
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

onMounted(() => {
  loadDatabases()
  loadHistory()
})
</script>

<style scoped>
.sql-history {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sql-content {
  cursor: pointer;
  color: #409eff;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.sql-content:hover {
  text-decoration: underline;
}

:deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
}
</style>
